// common/util.js
import permision from "@/js_sdk/wa-permission/permission.js"
export default {
	// 日期格式化函数
	formatDate(date, fmt) {
		if (fmt == null) fmt = 'yyyy.MM.dd';
		let daa = new Date(Number(date) * 1000);
		var o = {
			"M+": daa.getMonth() + 1, //月份 
			"d+": daa.getDate(), //日 
			"h+": daa.getHours(), //小时 
			"m+": daa.getMinutes(), //分 
			"s+": daa.getSeconds(), //秒 
			"q+": Math.floor((daa.getMonth() + 3) / 3), //季度 
			"S": daa.getMilliseconds() //毫秒 
		};
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(RegExp.$1, (daa.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt))
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
					.length)));
		return fmt;
	},
	// 获取当前时间  时：分
	getNowHour() {

		const currentTime = new Date();
		const hours = currentTime.getHours();
		const minutes = currentTime.getMinutes();
		const seconds = currentTime.getSeconds();
		let h = hours < 10 ? '0' + hours : hours,
			m = minutes < 10 ? '0' + minutes : minutes
		return h + ':' + m
	},
	// 获取两个时间段之间的 日期数据
	getDatesBetween(startDate, endDate) {
		const dates = [];
		const current = new Date(startDate);

		while (current <= endDate) {
			dates.push(this.formatDate(new Date(current).getTime() / 1000).replace(new RegExp(/\./g, 'g'), "-"));
			current.setDate(current.getDate() + 1);
		}

		return dates;
	},
	//  多选时间  按每周分割
	groupByWeeksAndMonths(dates) {
		// Helper function to parse and sort dates
		function parseAndSortDates(dates) {
			return dates.map(date => new Date(date)).sort((a, b) => a - b);
		}

		// Helper function to get the Sunday of the week for a given date
		function getSunday(date) {
			const day = date.getDay();
			const diff = date.getDate() - day;
			const sunday = new Date(date);
			sunday.setDate(diff);
			return sunday;
		}

		// Helper function to check if two dates are in the same month
		function isSameMonth(date1, date2) {
			return date1.getMonth() === date2.getMonth() && date1.getFullYear() === date2.getFullYear();
		}

		// Parse and sort the input dates
		let sortedDates = parseAndSortDates(dates);

		// Initialize the result array
		let result = [];
		let currentWeek = [];
		let currentSunday = getSunday(sortedDates[0]);
		let currentMonth = sortedDates[0].getMonth();

		// Loop through the sorted dates and group by weeks and months
		for (let i = 0; i < sortedDates.length; i++) {
			let date = sortedDates[i];
			let dateString = date.toISOString().split('T')[0];

			// Check if the date falls within the current week (Sunday to Saturday)
			if (date >= currentSunday && date < new Date(currentSunday.getTime() + 7 * 24 * 60 * 60 * 1000)) {
				// Check if the date is in the same month
				if (isSameMonth(date, sortedDates[i > 0 ? i - 1 : i])) {
					currentWeek.push(dateString);
				} else {
					result.push(currentWeek);
					currentWeek = [dateString];
					currentMonth = date.getMonth();
				}
			} else {
				result.push(currentWeek);
				currentWeek = [dateString];
				currentSunday = getSunday(date);
				currentMonth = date.getMonth();
			}
		}

		// Add the last week to the result if it is not empty
		if (currentWeek.length > 0) {
			result.push(currentWeek);
		}
		return result;
	},
	// 获取第二天
	getNextDays(date) {
		var today = new Date(date);
		today.setTime(today.getTime() + 24 * 60 * 60 * 1000);
		var tomorrow = today.getFullYear() + "." + ('0' + (today.getMonth() + 1)).slice(-2) + "." + ('0' + today
				.getDate())
			.slice(-2);
		return tomorrow
	},
	// 获取xx天后日期
	fun_date(nowDate, aa) {
		var date1 = new Date(nowDate),
			time1 = date1.getFullYear() + "." + (date1.getMonth() + 1) + "." + date1.getDate(); //time1表示当前时间
		var date2 = new Date(date1);
		date2.setDate(date1.getDate() + aa);
		var time2 = date2.getFullYear() + "." + (date2.getMonth() + 1) + "." + date2.getDate();
		return time2;
	},
	// 获取一周数据
	getWeekArray(date) {
		let nowDate = new Date(date)
		const weekStart = nowDate.getDate() - nowDate.getDay();
		const weekEnd = weekStart + 6;
		const weekDates = [];
		for (let i = 0; i < 7; i++) {
			const day = new Date(nowDate);
			day.setDate(weekStart + i);
			weekDates.push(day.getFullYear() + "-" + ('0' + (day.getMonth() + 1)).slice(-2) + "-" + ('0' + day
				.getDate()).slice(-2));
		}
		return weekDates;
	},
	// 图片预览
	preViewImage(img_url) {
		uni.previewImage({
			urls: img_url,
			longPressActions: {
				itemList: ['发送给朋友', '保存图片'],
				success: async function(data) {
					let res = await downLoadFile(img_url[data.index])
					if (data.tapIndex == 0) {
						uni.shareWithSystem({
							type: 'image',
							imageUrl: res.tempFilePath
						})
					} else if (data.tapIndex == 1) {
						if (res.statusCode === 200) {
							uni.showToast({
								icon: 'success',
								title: "下载成功"
							})
						} else {
							uni.showToast({
								icon: 'error',
								title: "下载失败"
							})
						}
					}
				},
				fail: function(err) {
					console.log(err.errMsg);
				}
			}
		});
	},
	//  ios 短振
	vibRateShort() {
		if (plus.os.name == 'iOS') {
			var UIImpactFeedbackGenerator = plus.ios.importClass(
				'UIImpactFeedbackGenerator',
			);
			var impact = new UIImpactFeedbackGenerator();
			impact.prepare();
			impact.init(1);
			impact.impactOccurred();
		} else {
			uni.vibrateShort();
		}
	},

	getAuth(ios_text, android_text) {
		// 获取系统信息
		const systemInfo = uni.getSystemInfoSync();
		// 判断是否为iOS设备
		const isIOS = systemInfo.platform === 'ios';
		if (isIOS) {
			return permision.judgeIosPermission(ios_text)
		} else {
			return requestAndroidPermission(android_text)
		}
	},
	async requestAndroidPermission(permisionID) {
		var result = await permision.requestAndroidPermission(permisionID)
		var strStatus
		if (result == 1) {
			strStatus = true
		} else {
			strStatus = false
			uni.showModal({
				title: '提示',
				content: '请先打开麦克风权限',
				success: function(res) {
					if (res.confirm) {
						permision.gotoAppPermissionSetting()
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				},
			});
		}
		return strStatus
	},
	scrollBottom(view) {
		setTimeout(() => {
			uni.pageScrollTo({
				duration: 0, // 过渡时间
				selector: view, // 滚动的实际距离
			})
		}, 100)
	}
};